package xyz.zhno.project.gateway.filter;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import xyz.zhno.project.commons.core.exception.ProjectExceptionCodeEnum;
import xyz.zhno.project.commons.core.exception.ProjectTokenException;
import xyz.zhno.project.commons.core.util.JwtUtils;

/**
 * 认证过滤器，判断是否登录
 * @author zh_o
 * @date 2020-11-01
 */
@Slf4j
@Component
public class AuthenticationFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        // 拦截路径待完善
        if (true) {
            return response.setComplete();
        }
        // 获取当前访问所携带令牌
        String tokenName = "Access-Token";
        String token = headers.getFirst(tokenName);
        // 验证令牌
        try {
            JwtUtils.verify(token);
        } catch (Exception e) {
            // 异常类型待拓展
            log.error("Exception: {}, Message: {}, Time: {} " + "\r\n" + " StackTrace: [{}]", e.getClass(), e.getMessage(), DateUtil.now(), ExceptionUtil.stacktraceToString(e));
            throw new ProjectTokenException(ProjectExceptionCodeEnum.USER_AUTHENTICATION_FAILED);
        }
        return response.setComplete();
    }


}
